<template>
  <el-dialog
    ref="SelectFlowObj"
    title="选择流程节点"
    width="60%"
    :visible.sync="params.visible"
    :close-on-click-modal="false"
    @close="params.visible = false"
  >
    <el-row :gutter="20">
      <el-col :span="12">
        <compTree
          ref="tree"
          :show-search="false"
          :comp-tree-height="350"
          :highlight-current="true"
          :tree-data="treeData"
          :tree-default-expanded-keys="treeDefaultExpandedKeys"
          :tree-node-select="treeNodeSelect"
        />
      </el-col>
      <el-col :span="12">
        <compTree
          ref="tree2"
          :show-search="false"
          :tree-show-checkbox="params.ismutil"
          :comp-tree-height="350"
          :tree-data="treeDataForNode"
          :tree-default-checked-keys="treeDefaultCheckedKeys"
          :tree-node-select="treeNodeSelect2"
          :tree-default-expanded-keys="treeDefaultExpandedKeys2"
          @treeNodeCheck="treeNodeCheck"
        />
      </el-col>
    </el-row>
    <dialog-btn slot="footer" />
  </el-dialog>
</template>
<script>
/**
 * 入参
 *  id,                   // 传入方式 this.$set(this.params, 'id', id)
 *  ismulti 是否多选       // 传入方式 this.$set(this.params, 'ismulti', false)
 *  isNullSelect          // 传入方式
 * 出参
 *  name 流程名
 *  id 流程id
 * 出参传出方式 this.ok({ name, id })
 */
import { getRpaFlowList, getFlowInfo } from '@/api/flow'
import { ParamArr, SQLTable } from '../../../public/js/paramarr'
import Global from '../../../public/js/global'

export default {
  props: {
    params: {
      type: Object,
      default() {
        return {
          visible: true, // 是否显示当前窗口
          flowId: '', // 流程id
          objId: '', // 流程节点id
          ismutil: false// 多节点
        }
      }
    }
  },
  data() {
    return {
      treeData: [],
      treeDataForNode: [],
      data: {},
      showCheckbox: false, // 是否显示checkbox
      node: {}, // 当前点击的节点
      flowNode: {},
      checkedNodes: [], // checkbox选中的所有节点
      selectParams: {},
      treeDefaultCheckedKeys: [],
      treeDefaultExpandedKeys: [],
      treeDefaultExpandedKeys2: []
    }
  },
  created() {
    this.initWindow()
  },
  methods: {
    initWindow() {
      getRpaFlowList(new ParamArr()).then(vPar => {
        const nodes = []
        const nodeMap = new Map()
        var selectNode = ''
        let table = new SQLTable(vPar.getTable('k_flow_group'))
        table.first()
        while (!table.eof()) {
          const pnode = Global.getTreeviewPNode(nodeMap, nodes, table.getValueByName('PID'))
          const node = {}
          node['id'] = table.getValueByName('ID')
          node['name'] = table.getValueByName('Name')
          node['text'] = node['name']
          node['icon'] = 'wenjianyi'
          node['type'] = 0
          node['folder'] = true
          pnode.push(node)
          nodeMap.set(node['id'], node)
          table.next()
        }
        table = new SQLTable(vPar.getTable('k_flow_info'))
        table.first()
        while (!table.eof()) {
          const pnode = Global.getTreeviewPNode(nodeMap, nodes, table.getValueByName('PID'))
          const node = {}
          node['id'] = table.getValueByName('FlowID')
          node['name'] = table.getValueByName('FlowName')
          node['text'] = node['name']
          node['icon'] = 'liuchen'
          node['type'] = 1
          if (this.params.flowId === node['id']) {
            selectNode = node
            this.treeDefaultExpandedKeys.push(table.getValueByName('PID'))
          }
          pnode.push(node)
          nodeMap.set(node['id'], node)
          table.next()
        }
        this.treeData = nodes
        if (this.params.flowId) {
          this.$refs.tree.setSelect(this.params.flowId)
          this.treeNodeSelect(selectNode)
        }
      })
    },
    treeNodeSelect(node) {
      this.node = node
      if (node.folder) return
      var vPar = new ParamArr()
      vPar.setStr('FlowID', node.id)
      vPar.setBool('LoadQuoteFlow', true)
      vPar.setBool('WebJson', true)
      getFlowInfo(vPar).then(this.lpfInitFlowObj)
    },
    treeNodeSelect2(node) {
      this.flowNode = node
    },
    lpfInitFlowObj(vPar) {
      if (!vPar.has('Obj')) {
        return
      }
      var jsonData = Global.parseWebJson(vPar.getBlobStr('Obj'))
      var lpChart = Global.parseWebJson(jsonData[2].Data)
      if (Object.keys(jsonData).length === 0) {
        return
      }
      var nodes = []
      this.getFlow(jsonData[0], nodes, '', lpChart) // 遍历
      nodes = this.flat2tree(nodes)
      this.treeDataForNode = nodes
      if (this.flowNode) {
        this.$refs.tree2.setSelect(this.flowNode['id'])
        this.treeDefaultExpandedKeys2.push(this.flowNode['pid'])
      }
    },
    flat2tree(jsonData) {
      var result = []; var temp = {}; var i = 0; var j = 0; var len = jsonData.length
      for (; i < len; i++) {
        temp[jsonData[i]['id']] = jsonData[i] // 以id作为索引存储元素，可以无需遍历直接定位元素
      }
      for (; j < len; j++) {
        var currentElement = jsonData[j]

        var tempCurrentElementParent = temp[currentElement['pid']] // 临时变量里面的当前元素的父元素
        if (tempCurrentElementParent) { // 如果存在父元素
          if (!tempCurrentElementParent['nodes']) { // 如果父元素没有chindren键
            tempCurrentElementParent['nodes'] = [] // 设上父元素的nodes键
          }
          tempCurrentElementParent['nodes'].push(currentElement) // 给父元素加上当前元素作为子元素
          currentElement['pathName'] = tempCurrentElementParent.name
        } else { // 不存在父元素，意味着当前元素是一级元素
          currentElement.pathName = currentElement.name
          result.push(currentElement)
        }
      }
      return this.createdPathName(result)
    },
    createdPathName(nodes, pName) {
      for (var i = 0; i < nodes.length; i++) {
        if (nodes[i].nodes) { // 父级存在子节点nodes
          if (pName !== undefined) {
            if (this.params.ismutil) { nodes[i].pathName = pName + '/' + nodes[i].name } else { nodes[i].pathName = pName + '\\' + nodes[i].name }
          }
          this.createdPathName(nodes[i].nodes, nodes[i].pathName)
        } else {
          if (pName !== undefined) {
            if (this.params.ismutil) { nodes[i].pathName = pName + '/' + nodes[i].name } else { nodes[i].pathName = pName + '\\' + nodes[i].name }
          }
        }

        // 回显
        if (this.params.ismutil) {
          var pathName = this.params.pathName.split(',')
          if (pathName.includes(nodes[i]['pathName'])) {
            this.checkedNodes.push(nodes[i])
            this.treeDefaultCheckedKeys.push(nodes[i]['id'])
          }
        } else {
          if (nodes[i].pathName === this.params.pathName) {
            this.flowNode = nodes[i]
          }
        }
      }
      return nodes
    },
    getFlow(obj, nodes, orgObj, lpChart) {
      for (var i = 0; i < obj.length; i++) {
        // 每一个流程数据
        var lpObj = obj[i]
        var data = Global.parseWebJson(lpObj.Data)
        var node = {}
        // if (data.ObjectType == '0' || data.ObjectType == '1')//均不显示开始和结束
        //    continue;
        if (lpObj.SubFlow) {
          // node['text'] = fmtTreeviewNodeText(getObjText(lpObj), nodeCollapseIcon_new);
          node['folder'] = 1
          // 嵌套内容
          var subObjs = []
          var rootObj = null
          for (var j = 0; j < lpObj.Sub_L; j++) {
            var subObj = ''
            if (lpObj[Global.strFormat('Sub_{0}_{1}', lpObj.Sub_ID, j)]) {
              subObj = Global.parseWebJson(lpObj[Global.strFormat('Sub_{0}_{1}', lpObj.Sub_ID, j)])
              subObj.pid = lpObj.Sub_ID
              subObjs.push(subObj)
            } else if (orgObj[Global.strFormat('Sub_{0}_{1}', lpObj.Sub_ID, j)]) {
              subObj = Global.parseWebJson(orgObj[Global.strFormat('Sub_{0}_{1}', lpObj.Sub_ID, j)])
              subObj.pid = lpObj.Sub_ID
              subObjs.push(subObj)
              rootObj = orgObj
            }
          }
          if (rootObj != null) {
            this.getFlow(subObjs, nodes, rootObj, lpChart)
          } else {
            this.getFlow(subObjs, nodes, lpObj, lpChart)
          }
          // 递归
        }
        if (lpObj.pid) { node['pid'] = lpObj.pid }
        node['id'] = lpObj.Sub_ID || Global.getGuid()
        node['objId'] = lpObj.ID
        node['name'] = this.getObjText(lpObj)
        node['text'] = this.getObjText(lpObj)
        if (node['folder'] !== 1) {
          node['icon'] = 'wenbenmoban'
        }
        node['level'] = Global.getLevelText(data.R_Level)
        node['color'] = Global.getLevelColor(data.R_Level)
        nodes.push(node)
      }
      return nodes
    },
    getObjText(lpObj) {
      var data = Global.parseWebJson(lpObj.Data)
      switch (Global.getJsonInt(data, 'ObjectType')) {
        case 0/* 开始*/:
          return '开始'
        case 1/* 结束*/:
          return '结束'
        case 2/* 操作*/:
          return data['TargetText']
        case 3/* 确认*/:
          if (Global.parseWebJson(lpObj['Data']).ConfirmName !== undefined) { return Global.parseWebJson(lpObj['Data']).ConfirmName.replace(/,/g, '，') } else { return lpObj['Text_TopLeft'].replace(/,/g, '，') }
        case 4/* 汇总*/:
          return '汇总'
        case 5/* 提示*/:
          return Global.strFormat('提示{0}', lpObj['Text_TopLeft'])
        case 6/* 引用*/:
          return lpObj['Text_TopLeft']
        case 7/* 嵌套*/:
          return lpObj['Text_TopLeft']
        case 8/* 组件*/:
          return Global.strFormat('({0}).({1})', lpObj['Text_ClientBottom'], lpObj['Text_TopLeft'])
      }
    },
    // 节点点击事件 获取所有选中流程
    treeNodeCheck(a, b) {
      this.checkedNodes = b.checkedNodes // 选中的所有节点
    },
    confirm() {
      var data = {}
      if (this.params.ismutil) {
        var nodes = this.checkedNodes
        // nodes = $('#dlgSelectFlowNodeTree').treeview('getChecked')
        var pathName = []
        var objId = []
        if (nodes.length < 1) { return this.$message.warning('请选择流程节点') }
        nodes.forEach(item => {
          if (item.folder !== 1) {
            objId.push(item.objId)
            pathName.push(item.pathName)
          }
        })
        data = {
          flowId: this.node.id,
          objId: objId.join(','),
          text: `[${objId.length}]个流程节点`,
          pathName: pathName.join(',')
        }
      } else {
        var node = this.flowNode
        if (Object.keys(node) === 0) {
          return this.$message.warning('请选择流程节点')
        }
        data = {
          flowId: this.node.id,
          objId: node.objId,
          text: node.name,
          pathName: node.pathName
        }
      }
      // 如果当前传入回调则使用回调
      if (this.params.confirm !== undefined) {
        this.params.confirm(data)
      } else {
        this.$emit('confirm', data)
      }
    }
  }
}
</script>

<style scoped>
</style>
